package com.pzr.soccer.config;

import cn.hutool.json.JSON;
import com.google.gson.Gson;
import com.pzr.soccer.domain.User;
import com.pzr.soccer.user.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class SetAdditionalInfoToTokenConverter extends DefaultUserAuthenticationConverter {

    /**
     * 这个方法把额外的信息添加进jwt token （默认只添加用户名，权限）
     * 这里额外添加了用户id
     * 方法将会在授权服务器起作用
     * @param authentication
     * @return
     */

   @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<String, Object>();
       // response.put(USERNAME, authentication.getName());   源码里面的，不知道USERNAME是什么，注释掉吧
       log.info("set additional infos...");
       Object principal = authentication.getPrincipal();
       //不要强制转换principal, 用json转化，不然各种莫名其妙的坑

       Gson gson=new Gson();
       String jsonStr= gson.toJson(principal);
       User user=gson.fromJson(jsonStr,User.class);

       //加上自定义的用户名和id
       response.put("id", user.getId());
       response.put("username", user.getUsername());
       response.put("email", user.getEmail());
       response.put("mobile", user.getPhone());

        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }


    //懒得写， 从源码复制过来的
    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        if (!map.containsKey(AUTHORITIES)) {
            return List.of();
        }
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }

}
